import { computed, ref } from 'vue'
import dayjs from 'dayjs'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
export function useObserver (apiFunc) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      // 当组件出现在可视区域时  才发请求
      if (isIntersecting) {
        apiFunc()
        // 调接口之后需要取消监听
        stop()
      }
      console.log(isIntersecting)
    }
  )
  return target
}

export function useCountDown (time) {
  const countTime = ref(0)
  const countTimeText = computed(() => {
    return dayjs.unix(countTime.value).format('mm分ss秒')
  })
  const { pause, resume } = useIntervalFn(() => {
    if (countTime.value <= 0) {
      pause()
      return
    }
    countTime.value--
  }, 1000)
  const start = (countDown) => {
    countTime.value = countDown || time
    resume()
  }
  // countTime  需要用到的倒计时事件
  // start 倒计时开始方法
  // pause 暂停
  // resume 继续
  return {
    countTime,
    countTimeText,
    start,
    pause,
    resume
  }
}
